package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@Service
public class DtsPermissionServiceImpl implements DtsPermissionService {

    @Autowired
    DtsPermissionMapper permissionMapper;

    @Override
    public Set<String> findPermByIds(Integer[] roleIds) {
        LambdaQueryWrapper<DtsPermission> qw = new LambdaQueryWrapper<>();
        qw.in(DtsPermission::getRoleId, roleIds);

        List<DtsPermission> permissionList = permissionMapper.selectList(qw);


        Set<String> permissions = permissionList.stream().map(permission -> {
            return permission.getPermission();
        }).collect(Collectors.toSet());

        return permissions;
    }

    @Override
    public void updatePermission(Integer roleId, ArrayList<String> permissions) {
        //1.  删除该角色拥有的权限
        LambdaQueryWrapper<DtsPermission> qw = new LambdaQueryWrapper<>();
        qw.eq(DtsPermission::getRoleId, roleId);

        permissionMapper.delete(qw);
        //2. 给该角色添加新的权限
        if(permissions != null && permissions.size() > 0) {
            for (String permission : permissions) {
                DtsPermission dtsPermission = new DtsPermission();
                dtsPermission.setDeleted(false);
                dtsPermission.setUpdateTime(new Date());
                dtsPermission.setAddTime(new Date());
                dtsPermission.setRoleId(roleId);
                dtsPermission.setPermission(permission);

                permissionMapper.insert(dtsPermission);
            }
        }



    }
}
